package com.ny.zmb.openapi.jh.service;

import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import com.ny.zmb.openapi.constant.JHConstant;
import com.ny.zmb.openapi.jh.JhEnum;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class JHTokenService implements ApplicationRunner {

    private static Map<String,Object> dataMap = null;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        getAccessToken();
    }

    public static void main(String[] args) {
        String accessToken = getAccessToken();
        System.out.println(accessToken);
    }
    /**
     * 获取token信息
     * @return
     */
    public static String getAccessToken(){
        if (null == dataMap){
            return accessToken().get("accessToken").toString();
        }
        Long accessExpires = (Long) dataMap.get("accessExpires");
        if (accessExpires < System.currentTimeMillis()){
            return accessToken().get("accessToken").toString();
        }
        System.out.println(dataMap);
        return dataMap.get("accessToken").toString();
    }

    /**
     * 生成用户信息
     * @return
     */
    public static Map<String,Object> accessToken(){
        String result = HttpClient.post(JHConstant.JH_BASE_URL + "/open/accessToken")
                .queryString("grantType", JHConstant.grantType)
                .queryString("appKey", JHConstant.appKey)
                .queryString("username", JHConstant.username)
                .queryString("password", JHConstant.password)
                .execute().asString();
        JSONObject reJson = JSONObject.parseObject(result);
        reJson = JhEnum.get(reJson);
        if (0 == reJson.getInteger("code"))
        {
            JSONObject data = reJson.getJSONObject("data");
            Map<String,Object> map = new ConcurrentHashMap<>();
            for (String key : data.keySet()) {
                map.put(key,data.get(key));
            }
            System.out.println(map);
            dataMap = map;
            return map;
        }
        throw new RuntimeException(reJson.getString("msg"));
    }
}
